package de.wiroo.setup.web.common;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;

/**
 * Actions that can be applied to a single already existing entity. The default
 * actions are delete, update and read.
 * 
 * @author stefan
 * 
 * @param <T>
 */
public class ActionPanel<M> extends Panel {

	public ActionPanel(String id) {
		super(id);
		init();
	}

	public ActionPanel(String id, IModel<M> model) {
		super(id, model);
		init();
	}

	protected void init() {
		Form<M> form = new Form<M>("form");
		RepeatingView repeater = new RepeatingView("buttons");
		form.add(repeater);
		add(form);
	}

	public ActionPanel<M> withActions(List<IAction<?, IModel<M>>> actions) {
		return withActions(false, actions);
	}

	/**
	 * 
	 * @param action
	 *            the action ID
	 * @param defaultFormProcessing
	 * @return this
	 */
	public ActionPanel<M> withActions(boolean defaultFormProcessing,
			List<IAction<?, IModel<M>>> actions) {

		RepeatingView repeater = getRepeater();
		for (IAction<?, IModel<M>> entityAction : actions) {
			repeater.add(createActionButton(repeater.newChildId(), getModel(),
					entityAction, defaultFormProcessing));
		}
		return this;
	}

	public ActionPanel<M> withNavigation(final String kind) {
		RepeatingView repeater = getRepeater();
		repeater.add(new IconButton(repeater.newChildId(), null) {

			@Override
			protected String getKind() {
				// TODO: map navigation kind to button kind ...
				return IconButton.SHOW;
			}

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				// TODO Auto-generated method stub
				// TODO: Is this the proper broadcast type?
				send(this.getPage(), Broadcast.BREADTH, new NavigationEvent<M>(
						kind, ActionPanel.this.getModel(),
						target));
			}

		});
		return this;
	}

	private RepeatingView getRepeater() {
		return (RepeatingView) get("form").get("buttons");
	}

	private <R> Component createActionButton(String id, IModel<M> model,
			final IAction<R, IModel<M>> action, boolean defaultFormProcessing) {
		return new ActionButton<R, IModel<M>>(id, null) {

			@Override
			protected IModel<M> getParamForAction() {
				return ActionPanel.this.getModel();
			}

			@Override
			protected IAction<R, IModel<M>> getAction() {
				return action;
			}

		}.setDefaultFormProcessing(defaultFormProcessing);
	}

	@SuppressWarnings("unchecked")
	protected IModel<M> getModel() {
		return (IModel<M>) getDefaultModel();
	}

}
